﻿using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Data.DataSources {
	public class ProfilesDataSource : ObjectDataSourceBase {
		public override DataView SelectEx() {
			ProfileInfoCollection ps = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
			DataTable dt = new DataTable();
			dt.Columns.Add("ID");
			dt.Columns.Add("UserName");
			dt.Columns.Add("Name");
			foreach (SettingsProperty sp in ProfileCommon.Properties)
				dt.Columns.Add(sp.Name);
			foreach (ProfileInfo p in ps) {
				DataRow row = dt.NewRow();
				row["ID"] = p.UserName;
				row["UserName"] = p.UserName;
				row["Name"] = Regex.Match(p.UserName, @"[^\\]+$").Value;
				ProfileCommon pc = ((ProfileCommon)ProfileCommon.Create(p.UserName));
				foreach (SettingsProperty sp in ProfileCommon.Properties)
					row[sp.Name] = pc[sp.Name] + "";
				dt.Rows.Add(row);
			}
			dt.DefaultView.RowFilter = Wheres().Replace("WHERE ","");
			return dt.DefaultView;
		}
		public override void DeleteEx(object ID) {
			//if ((ID+"").Contains("\\")) throw new NotSupportedException("This is real user's profiles .");
			ProfileManager.DeleteProfiles(new string[] { ID+"" });
		}
		public void Update(string ID,string Username, string FilterLast) {
			ProfileCommon prof = new ProfileCommon().GetProfile(ID);
			if (ID != Username) {
				bool newProfExists = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)[Username] != null;
				ProfileCommon profNew = new ProfileCommon().GetProfile(Username);
				foreach (SettingsProperty sp in ProfileCommon.Properties)
					profNew[sp.Name] = prof[sp.Name];
				profNew.FilterLast = FilterLast + "";
				profNew.Save();
				if (!newProfExists) DeleteEx(ID);//move
			} else {
				prof.FilterLast = FilterLast + "";
				prof.Save();
			}
		}
		public static void Insert(string Username) {
			ProfileCommon pNew = (ProfileCommon)ProfileCommon.Create(Username);
			pNew.Filters = pNew.Filters;
			pNew.Save();
		}
	}
}